package com.ruoyi.monitor.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.base.domain.BusWaterSegment;
import com.ruoyi.base.domain.BussinessItemVo;
import com.ruoyi.base.mapper.PublicToolsMapper;
import com.ruoyi.base.service.IBusWaterSegmentService;
import com.ruoyi.base.service.PublicToolsService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.monitor.domain.BusWaterAutomonitorHourdata;
import com.ruoyi.monitor.service.IBusWaterAutomonitorHourdataService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.monitor.mapper.BusWaterAutomonitorevaluateHourdataMapper;
import com.ruoyi.monitor.domain.BusWaterAutomonitorevaluateHourdata;
import com.ruoyi.monitor.service.IBusWaterAutomonitorevaluateHourdataService;
import org.springframework.util.CollectionUtils;

import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;

/**
 * 自动站断面小时评价数据Service业务层处理
 *
 * @author maliang
 * @date 2025-07-31
 */
@Service
public class BusWaterAutomonitorevaluateHourdataServiceImpl implements IBusWaterAutomonitorevaluateHourdataService {
    @Autowired
    private BusWaterAutomonitorevaluateHourdataMapper busWaterAutomonitorevaluateHourdataMapper;
    @Autowired
    private PublicToolsService publicToolsService;
    @Autowired
    private IBusWaterAutomonitorHourdataService busWaterAutomonitorHourdataService;
    @Autowired
    private IBusWaterSegmentService busWaterSegmentService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private PublicToolsMapper publicToolsMapper;

    /**
     * 查询自动站断面小时评价数据
     *
     * @param id 自动站断面小时评价数据主键
     * @return 自动站断面小时评价数据
     */
    @Override
    public BusWaterAutomonitorevaluateHourdata selectBusWaterAutomonitorevaluateHourdataById(String id) {
        return busWaterAutomonitorevaluateHourdataMapper.selectBusWaterAutomonitorevaluateHourdataById(id);
    }

    /**
     * 查询自动站断面小时评价数据列表
     *
     * @param busWaterAutomonitorevaluateHourdata 自动站断面小时评价数据
     * @return 自动站断面小时评价数据
     */
    @Override
    public List<BusWaterAutomonitorevaluateHourdata> selectBusWaterAutomonitorevaluateHourdataList(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata) {
        if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getCountyCode())) {
            busWaterAutomonitorevaluateHourdata.setCountyCodeList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getCountyCode().split(",")));
        }
        if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getSegmentid()) && busWaterAutomonitorevaluateHourdata.getSegmentid().contains(",")) {
            busWaterAutomonitorevaluateHourdata.setSegmentidList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getSegmentid().split(",")));
            busWaterAutomonitorevaluateHourdata.setSegmentid(null);
        }
        if(busWaterAutomonitorevaluateHourdata.getIsitontimedata() != null && busWaterAutomonitorevaluateHourdata.getIsitontimedata()==1){
            busWaterAutomonitorevaluateHourdata.setIsitontimedata(0);
        }else if(busWaterAutomonitorevaluateHourdata.getIsitontimedata() != null && busWaterAutomonitorevaluateHourdata.getIsitontimedata()==0){
            busWaterAutomonitorevaluateHourdata.setIsitontimedata(null);
        }
        if("0".equals(busWaterAutomonitorevaluateHourdata.getIsoverstandard())){
            busWaterAutomonitorevaluateHourdata.setIsoverstandard(null);
        }
        return busWaterAutomonitorevaluateHourdataMapper.selectBusWaterAutomonitorevaluateHourdataList(busWaterAutomonitorevaluateHourdata);
    }

    @Override
    public List<Map> selectBusWaterAutomonitorevaluateHourdataAndItemList(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata) {
        List<Map> mapList = new ArrayList<>();
        List<BusWaterAutomonitorevaluateHourdata> list = selectBusWaterAutomonitorevaluateHourdataList(busWaterAutomonitorevaluateHourdata);
        Page<BusWaterAutomonitorevaluateHourdata> page = (Page)list;

        //查询标准值
        Map<String, Object>standardcategoryMap = new HashMap<>();
        standardcategoryMap.put("waterBody", "1");
        List<Map<String, Object>> wqBasStandardcategorylist = publicToolsMapper.busStandardcategorylist(standardcategoryMap);

        if (!CollectionUtils.isEmpty(list)) {
            //获取检测因子配置
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode("Auto");
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            for (BusWaterAutomonitorevaluateHourdata waterAutomonitorevaluateHourdata : list) {
                Map map = JSONObject.parseObject(JSONObject.toJSONString(waterAutomonitorevaluateHourdata), Map.class);
                String overMessage = "";
                if (!CollectionUtils.isEmpty(itemList)) {
                    for (Map<String, Object> stringObjectMap : itemList) {
                        //查看是否超标
                        String itemName=String.valueOf(stringObjectMap.get("itemName"));
                        String isEvalute= StringUtils.getString(stringObjectMap.get("isEvalute"));
                        BusWaterAutomonitorHourdata param = new BusWaterAutomonitorHourdata();
                        param.setSegmentid(waterAutomonitorevaluateHourdata.getSegmentid());
                        param.setItemcode(StringUtils.getString(stringObjectMap.get("itemCode")));
                        param.setSampletime(waterAutomonitorevaluateHourdata.getSampletime());
                        List<BusWaterAutomonitorHourdata> hourdataList = busWaterAutomonitorHourdataService.selectBusWaterAutomonitorHourdataList(param);
                        String evalue ="";
                        if (!CollectionUtils.isEmpty(hourdataList)) {
                            BusWaterAutomonitorHourdata hourdata = hourdataList.get(0);
                            DecimalFormat df = new DecimalFormat("###.#####");
                             evalue = df.format(hourdata.getEffectivevalue());
//                            map.put(StringUtils.getString(stringObjectMap.get("eNName")), evalue);
                            if("1".equals(isEvalute)){
                                List<Map<String, Object>> sunmapsWaterTypelist =  wqBasStandardcategorylist.stream().filter(s->String.valueOf(s.get("itemCode")).equals(String.valueOf(stringObjectMap.get("itemCode"))) && String.valueOf(s.get("level")).equals(String.valueOf(waterAutomonitorevaluateHourdata.getTargetlevel())) && String.valueOf(s.get("waterType")).equals("1")).collect(Collectors.toList());
                                String isoverstandard= hourdata.getIsoverstandard();
                                BigDecimal effectivevalue= hourdata.getEffectivevalue();
                                String overstandardtimes=hourdata.getOverstandardtimes();
                                if("1".equals(isoverstandard)){
                                    overMessage=overMessage+itemName+"(监测值："+df.format(effectivevalue)+stringObjectMap.get("unit");
//                                    if(StringUtils.isNotEmpty(overstandardtimes)){
//                                        overMessage=overMessage+",倍数："+overstandardtimes;
//                                    }
                                    if("15DE941F-A221-4D9C-8387-48B0E99F6E25".equals(String.valueOf(stringObjectMap.get("ItemCode")).toUpperCase())){
                                        overMessage=overMessage+",标准值：6~9";
                                    }else{
                                        if(StringUtils.isNotEmpty(sunmapsWaterTypelist) && sunmapsWaterTypelist.size()>0)    {
                                            Object  standardValue = sunmapsWaterTypelist.get(0).get("standardValue");
                                            overMessage=overMessage+",标准值:"+standardValue+stringObjectMap.get("unit");
                                        }
                                    }
                                    overMessage=overMessage+")、";
                                }
                            }
                        }
                        map.put(StringUtils.getString(stringObjectMap.get("eNName")), evalue);
                    }
                }

                if(StringUtils.isNotEmpty(overMessage)){
                    map.put("overstandarddescribe",overMessage.substring(0,overMessage.length()-1));
                }else{
                    map.put("overstandarddescribe","");
                }

                mapList.add(map);
            }
        }
        Page<Map> resPage = new Page<>();
        resPage.addAll(mapList);
        resPage.setTotal(page.getTotal());
        return resPage;
    }

    @Override
    public Map getLastData(String segmentId) {
        BusWaterAutomonitorevaluateHourdata param = new BusWaterAutomonitorevaluateHourdata();
        param.setSegmentid(segmentId);
        param.setLastSize(1);
        param.setIsitontimedata(1);
        List<BusWaterAutomonitorevaluateHourdata> list = selectBusWaterAutomonitorevaluateHourdataList(param);
        Map map = new HashMap();
        map.put("dataTime", "");
        Date lastDate = null;

        if (!CollectionUtils.isEmpty(list)) {
            map.put("dataTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", list.get(0).getSampletime()));
            lastDate = list.get(0).getSampletime();
        }
        List<Map> dataMapList = new ArrayList<>();
        //获取检测因子配置
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
        for (Map<String, Object> stringObjectMap : itemList) {
            Map dataMap = new HashMap();
            dataMap.put("itemName", StringUtils.getString(stringObjectMap.get("itemName")));
            dataMap.put("unit", StringUtils.getString(stringObjectMap.get("unit")));
            if (lastDate != null) {
                BusWaterAutomonitorHourdata dataparam = new BusWaterAutomonitorHourdata();
                dataparam.setSegmentid(segmentId);
                dataparam.setItemcode(StringUtils.getString(stringObjectMap.get("itemCode")));
                dataparam.setSampletime(lastDate);
                List<BusWaterAutomonitorHourdata> hourdataList = busWaterAutomonitorHourdataService.selectBusWaterAutomonitorHourdataList(dataparam);
                if (!CollectionUtils.isEmpty(hourdataList)) {
                    BusWaterAutomonitorHourdata hourdata = hourdataList.get(0);
                    dataMap.put("value", hourdata.getEffectivevalue());
                } else {
                    dataMap.put("value", "");
                }
            } else {
                dataMap.put("value", "");
            }
            dataMapList.add(dataMap);
        }
        map.put("dataMapList", dataMapList);
        return map;
    }

    /**
     * 新增自动站断面小时评价数据
     *
     * @param busWaterAutomonitorevaluateHourdata 自动站断面小时评价数据
     * @return 结果
     */
    @Override
    public int insertBusWaterAutomonitorevaluateHourdata(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata) {
        return busWaterAutomonitorevaluateHourdataMapper.insertBusWaterAutomonitorevaluateHourdata(busWaterAutomonitorevaluateHourdata);
    }

    /**
     * 修改自动站断面小时评价数据
     *
     * @param busWaterAutomonitorevaluateHourdata 自动站断面小时评价数据
     * @return 结果
     */
    @Override
    public int updateBusWaterAutomonitorevaluateHourdata(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata) {
        return busWaterAutomonitorevaluateHourdataMapper.updateBusWaterAutomonitorevaluateHourdata(busWaterAutomonitorevaluateHourdata);
    }

    /**
     * 批量删除自动站断面小时评价数据
     *
     * @param ids 需要删除的自动站断面小时评价数据主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorevaluateHourdataByIds(String[] ids) {
        return busWaterAutomonitorevaluateHourdataMapper.deleteBusWaterAutomonitorevaluateHourdataByIds(ids);
    }

    /**
     * 删除自动站断面小时评价数据信息
     *
     * @param id 自动站断面小时评价数据主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorevaluateHourdataById(String id) {
        return busWaterAutomonitorevaluateHourdataMapper.deleteBusWaterAutomonitorevaluateHourdataById(id);
    }

    @Override
    public Map overview(String id) {
        Map map = new HashMap();
        BusWaterSegment busWaterSegment = busWaterSegmentService.selectBusWaterSegmentByID(id);
        map.put("basinName", busWaterSegment.getBasinname());
        map.put("riverName", busWaterSegment.getRivername());
        map.put("county", busWaterSegment.getCounty());
        map.put("segmentCategory", busWaterSegment.getSegmentcategory());
        map.put("controlLevel", busWaterSegment.getControllevel());
        map.put("targetLevelName", busWaterSegment.getTargetlevelname());
        map.put("longitude", busWaterSegment.getLongitude());
        map.put("latitude", busWaterSegment.getLatitude());

        BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdataParam = new BusWaterAutomonitorevaluateHourdata();
        busWaterAutomonitorevaluateHourdataParam.setSegmentid(id);
        List<BusWaterAutomonitorevaluateHourdata> busWaterAutomonitorevaluateHourdataList = busWaterAutomonitorevaluateHourdataMapper.selectLastData(busWaterAutomonitorevaluateHourdataParam);
        if (!CollectionUtils.isEmpty(busWaterAutomonitorevaluateHourdataList)) {
            BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata = busWaterAutomonitorevaluateHourdataList.get(0);
            map.put("sampleTime", DateUtils.parseDateToStr("yyyy-MM-dd HH", busWaterAutomonitorevaluateHourdata.getSampletime()));
            map.put("waterQuality", busWaterAutomonitorevaluateHourdata.getWaterquality());
            map.put("segmentIndex", busWaterAutomonitorevaluateHourdata.getSegmentindex());
            map.put("isoverstandard", busWaterAutomonitorevaluateHourdata.getIsoverstandard());
            map.put("qualitylevelname", busWaterAutomonitorevaluateHourdata.getQualitylevelname());

            //获取检测因子配置
            List<Map> itemDataList = new ArrayList<>();
            List<Map> overstandardList = new ArrayList<>();
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode("Auto");

            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            for (Map<String, Object> stringObjectMap : itemList) {
                BusWaterAutomonitorHourdata param = new BusWaterAutomonitorHourdata();
                param.setSegmentid(busWaterAutomonitorevaluateHourdata.getSegmentid());
                param.setItemcode(StringUtils.getString(stringObjectMap.get("itemCode")));
                param.setSampletime(busWaterAutomonitorevaluateHourdata.getSampletime());
                List<BusWaterAutomonitorHourdata> hourdataList = busWaterAutomonitorHourdataService.selectBusWaterAutomonitorHourdataList(param);
                Map tmpMap = new HashMap();
                tmpMap.put("name", StringUtils.getString(stringObjectMap.get("itemName")));
                if (!CollectionUtils.isEmpty(hourdataList)) {
                    BusWaterAutomonitorHourdata hourdata = hourdataList.get(0);
                    tmpMap.put("value", hourdata.getEffectivevalue());
                    tmpMap.put("isOverStandard", hourdata.getIsoverstandard());
                    if ("1".equals(hourdata.getIsoverstandard())) {
                        overstandardList.add(tmpMap);
                    }
                } else {
                    tmpMap.put("value", "");
                    tmpMap.put("isOverStandard", "");
                }
                itemDataList.add(tmpMap);
            }
            map.put("itemDataList", itemDataList);
            map.put("overstandardList", overstandardList);
        } else {
            map.put("sampleTime", "");
            map.put("waterQuality", "");
            map.put("segmentIndex", "");
            //获取检测因子配置
            List<Map> itemDataList = new ArrayList<>();
            List<Map> overstandardList = new ArrayList<>();
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode("Auto");
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            for (Map<String, Object> stringObjectMap : itemList) {
                Map tmpMap = new HashMap();
                tmpMap.put("name", StringUtils.getString(stringObjectMap.get("itemName")));
                tmpMap.put("value", "");
                tmpMap.put("isOverStandard", "");
                itemDataList.add(tmpMap);
            }
            map.put("itemDataList", itemDataList);
            map.put("overstandardList", overstandardList);
        }
        return map;
    }

    @Override
    public Map statisItemCount(String id, String startTime, String endTime) {
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", startTime + " 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", endTime + " 23:59:59");

        List<Map> statisList = busWaterAutomonitorevaluateHourdataMapper.statisItemCount(id, startDate, endDate);

        Map<String, List<String>> itemDataList = new HashMap<>();

        while (!startDate.after(endDate)) {
            String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd", startDate);
            if (itemDataList.containsKey("dateList")) {
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            } else {
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            }
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                Map itemDataMap = new HashMap();
                itemDataMap.put("day", dayTime);
                itemDataMap.put("item", itemName);
                int count = 0;
                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String dataCount = StringUtils.getString(statisMap.get("dataCount"));
                    if (statisDay.equals(dayTime) && itemName.equals(statisItem)) {
                        count = Integer.valueOf(dataCount);
                        break;
                    }
                }
                if (itemDataList.containsKey(itemName)) {
                    List<String> dateList = itemDataList.get(itemName);
                    dateList.add(count + "");
                    itemDataList.put(itemName, dateList);
                } else {
                    List<String> dateList = new ArrayList<>();
                    dateList.add(count + "");
                    itemDataList.put(itemName, dateList);
                }
            }
            startDate = DateUtils.addDays(startDate, 1);
        }
        return itemDataList;
    }

    @Override
    public Map trendStatis(String id, String startTime, String endTime, String items) {
        List<String> queryItemList = new ArrayList<>();
        if (StringUtils.isNotEmpty(items)) {
            queryItemList = Arrays.asList(items.split(","));
        }
        Map<String, List<String>> itemDataList = new HashMap();

        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", startTime);
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", endTime);

        List<Map> statisList = busWaterAutomonitorevaluateHourdataMapper.trendStatis(id, startDate, endDate);

        Date preYearStartDate = DateUtils.addYears(startDate, -1);
        Date preYearEndDate = DateUtils.addYears(endDate, -1);
        List<Map> preYearstatisList = busWaterAutomonitorevaluateHourdataMapper.trendStatis(id, preYearStartDate, preYearEndDate);

        while (!startDate.after(endDate)) {
            String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd HH", startDate);
            if (itemDataList.containsKey("dateList")) {
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            } else {
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            }
            String dayTimeNoYear = DateUtils.parseDateToStr("MM-dd HH:mm", startDate);
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                if (!queryItemList.contains(itemName)) {
                    continue;
                }
                Map itemDataMap = new HashMap();
                itemDataMap.put("dataTime", dayTime);
                itemDataMap.put("item", itemName);
                String effectiveValue = "0";
                String onYeareffectiveValue = "0";

                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String effective = StringUtils.getString(statisMap.get("effectiveValue"));
                    if (statisDay.contains(dayTime) && itemName.equals(statisItem)) {
                        if (StringUtils.isNotEmpty(effective)) {
                            effectiveValue = effective;
                        }
                        break;
                    }
                }
                if (itemDataList.containsKey(itemName)) {
                    List<String> dataList = itemDataList.get(itemName);
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName, dataList);
                } else {
                    List<String> dataList = new ArrayList<>();
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName, dataList);
                }
                for (Map statisMap : preYearstatisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String effective = StringUtils.getString(statisMap.get("effectiveValue"));
                    if (statisDay.contains(dayTimeNoYear) && itemName.equals(statisItem)) {
                        if (StringUtils.isNotEmpty(effective)) {
                            onYeareffectiveValue = effective;
                        }
                        break;
                    }
                }
                if (itemDataList.containsKey(itemName + "_上期")) {
                    List<String> dataList = itemDataList.get(itemName + "_上期");
                    dataList.add(onYeareffectiveValue);
                    itemDataList.put(itemName + "_上期", dataList);
                } else {
                    List<String> dataList = new ArrayList<>();
                    dataList.add(onYeareffectiveValue);
                    itemDataList.put(itemName + "_上期", dataList);
                }
            }
            startDate = DateUtils.addHours(startDate, 1);
        }
        return itemDataList;
    }


    @Override
    public Map trendQuality(String id, String startTime, String endTime) {
        Map<String, List<String>> itemDataList = new HashMap();

        SysDictData sysDictDataParam = new SysDictData();
        sysDictDataParam.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataParam);
        List<String> levelList = new ArrayList<>();
        sysDictDataList.sort(Comparator.comparing(SysDictData::getDictSort).reversed());
        for (SysDictData sysDictData : sysDictDataList) {
            levelList.add(sysDictData.getDictLabel());
        }
        itemDataList.put("levelList", levelList);

        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", startTime);
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", endTime);

        BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdataParam = new BusWaterAutomonitorevaluateHourdata();
        busWaterAutomonitorevaluateHourdataParam.setSegmentid(id);
        busWaterAutomonitorevaluateHourdataParam.setStartTime(startDate);
        busWaterAutomonitorevaluateHourdataParam.setEndTime(endDate);
        List<BusWaterAutomonitorevaluateHourdata> statisList = busWaterAutomonitorevaluateHourdataMapper.selectBusWaterAutomonitorevaluateHourdataList(busWaterAutomonitorevaluateHourdataParam);

        while (!startDate.after(endDate)) {
            String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", startDate);
            if (itemDataList.containsKey("dateList")) {
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            } else {
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList", dateList);
            }
            String itemName = "level";

            Map itemDataMap = new HashMap();
            itemDataMap.put("dataTime", dayTime);
            itemDataMap.put("item", itemName);
            String level = "无类别";

            for (BusWaterAutomonitorevaluateHourdata statisMap : statisList) {
                String statisDay = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", statisMap.getSampletime());
                if (statisDay.equals(dayTime)) {
                    if (StringUtils.isNotEmpty(statisMap.getQualitylevelname())) {
                        level = statisMap.getQualitylevelname();
                    }
                    break;
                }
            }
            if (itemDataList.containsKey(itemName)) {
                List<String> dataList = itemDataList.get(itemName);
                dataList.add(level);
                itemDataList.put(itemName, dataList);
            } else {
                List<String> dataList = new ArrayList<>();
                dataList.add(level);
                itemDataList.put(itemName, dataList);
            }
            startDate = DateUtils.addHours(startDate, 1);
        }
        return itemDataList;
    }

    /*
    获取自动监测的历史数据，根据断面类型
     */
    @Override
    public List<Map> selectBusWaterAutomonitorevaluateHourdataAndItemListHistory(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata, String type) {
        List<Map> mapList = new ArrayList<>();
        //获取断面评价数据
        List<BusWaterAutomonitorevaluateHourdata> list = selectBusWaterAutomonitorevaluateHourdataList(busWaterAutomonitorevaluateHourdata);
        if (!CollectionUtils.isEmpty(list)) {
            //获取检测因子配置
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode(type);
            //获取水监测项目
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            BusWaterAutomonitorHourdata param = new BusWaterAutomonitorHourdata();
            if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getSegmentid()) && busWaterAutomonitorevaluateHourdata.getSegmentid().contains(",")) {
                param.setSegmentidList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getSegmentid().split(",")));
                param.setSegmentid(null);
            }
            if (!itemList.isEmpty()) {
                List<String> ItemcodeList = new ArrayList<>();
                for (Map<String, Object> stringObjectMap : itemList) {
                    ItemcodeList.add(StringUtils.getString(stringObjectMap.get("itemCode")));
                }
                param.setItemcodeList(ItemcodeList);
                param.setItemcode(null);
            }
            //获取水监测项目监测数据
            List<BusWaterAutomonitorHourdata> hourdataList = busWaterAutomonitorHourdataService.selectBusWaterAutomonitorHourdataList(param);
            //循环查询断面，项目监测数据
            for (BusWaterAutomonitorevaluateHourdata waterAutomonitorevaluateHourdata : list) {
                Map map = JSONObject.parseObject(JSONObject.toJSONString(waterAutomonitorevaluateHourdata), Map.class);
                if (!CollectionUtils.isEmpty(itemList)) {
                    for (Map<String, Object> stringObjectMap : itemList) {
                        if (!CollectionUtils.isEmpty(hourdataList)) {
                            BusWaterAutomonitorHourdata hourdata = hourdataList.stream().filter(data -> data.getSegmentid().equals(waterAutomonitorevaluateHourdata.getSegmentid())
                                            && data.getItemcode().equals(StringUtils.getString(stringObjectMap.get("itemCode"))) && data.getSampletime().equals(waterAutomonitorevaluateHourdata.getSampletime()))
                                    .findFirst().orElse(null);
                            if (hourdata != null) {
                                DecimalFormat df = new DecimalFormat("###.#####");
                                String evalue = df.format(hourdata.getEffectivevalue());
                                map.put(StringUtils.getString(stringObjectMap.get("eNName")), evalue);
                            } else {
                                map.put(StringUtils.getString(stringObjectMap.get("eNName")), "");
                            }
                        }
                    }
                }
                mapList.add(map);
            }
        }
        return mapList;
    }

    @Override
    public List<Map<String, Object>> getWaterAutoEvaluateHourList(Map<String, Object> params) {
        List<Map<String, Object>> resultList=new ArrayList<>();
        if (StringUtils.isEmpty(params.get("beginTime")!=null  ? params.get("beginTime").toString() : "") || StringUtils.isEmpty(params.get("endTime")!=null ? params.get("endTime").toString() : "")){
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-1)));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-1)));
        }else {
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.parseDate(params.get("beginTime").toString())));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.parseDate(params.get("endTime").toString())));
        }
        resultList = busWaterAutomonitorevaluateHourdataMapper.getWaterAutoEvaluateHourList(params);
        // 假如查询为空，再往前推一天查询
        if (StringUtils.isEmpty(resultList)){
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-2)));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-2)));
            resultList = busWaterAutomonitorevaluateHourdataMapper.getWaterAutoEvaluateHourList(params);
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getWaterAutoMonitorHourList(Map<String, Object> params) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (StringUtils.isEmpty(params.get("beginTime")!=null  ? params.get("beginTime").toString() : "") || StringUtils.isEmpty(params.get("endTime")!=null ? params.get("endTime").toString() : "")){
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-1)));
            params.put("endTime",  DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(DateUtils.getNowDate(),-1)));
        }else {
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.parseDate(params.get("beginTime").toString())));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.parseDate(params.get("endTime").toString())));
        }
        List<Map<String, Object>> dataList= busWaterAutomonitorevaluateHourdataMapper.getWaterAutoMonitorHourList(params);
        if(StringUtils.isNotEmpty(dataList)){
            //获取检测因子配置
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode("Auto");
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            // 对dataList 进行分组，按segmentId进行分组
            Map<String,List<Map<String, Object>>> segmentIdMap = dataList.stream().collect(
                    Collectors.groupingBy(map -> (String)map.get("segmentId"))
            );
            // 循环分组的数据
            segmentIdMap.forEach((segmentId, segmentIdList) -> {
                // 对segmentIdList 按时间分组sampleTime
                Map<String,List<Map<String, Object>>> segmentTimeMap = segmentIdList.stream().collect(
                        Collectors.groupingBy(map -> (String)map.get("sampleTime"))
                );
                // 循环分组的数据进行行转列
                segmentTimeMap.forEach((sampleTime, dataTimeList) -> {
                    Map<String,Object> dataMap = new HashMap();
                    dataMap.put("segmentId",dataTimeList.get(0).get("segmentId"));
                    dataMap.put("segmentName",dataTimeList.get(0).get("segmentName"));
                    dataMap.put("sampleTime",sampleTime);
                    dataTimeList.forEach(map -> {
                        itemList.forEach(itemMap -> {
                            String itemCode = StringUtils.getString(map.get("itemCode"));
                            if(itemCode.equals(itemMap.get("itemCode"))){
                                dataMap.put(itemMap.get("eNName").toString(),map.get("effectiveValue"));
                            }
                        });
                    });
                    resultList.add(dataMap);
                });
            });
        }
        return resultList;
    }

    /**
     * 查询业务自动监测小时数据最新数据列表
     *
     * @param busWaterAutomonitorevaluateHourdata 业务自动监测小时数据
     * @return 业务自动监测小时数据最新数据
     */
    public List<BusWaterAutomonitorevaluateHourdata> selectBusWaterAutomonitorevaluateNewHourdataList(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata) {
        if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getCountyCode())) {
            busWaterAutomonitorevaluateHourdata.setCountyCodeList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getCountyCode().split(",")));
        }
        if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getSegmentid()) && busWaterAutomonitorevaluateHourdata.getSegmentid().contains(",")) {
            busWaterAutomonitorevaluateHourdata.setSegmentidList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getSegmentid().split(",")));
            busWaterAutomonitorevaluateHourdata.setSegmentid(null);
        }

        return busWaterAutomonitorevaluateHourdataMapper.selectBusWaterAutomonitorevaluateNewHourdataList(busWaterAutomonitorevaluateHourdata);
    }

    /*
    获取自动监测的最新数据，根据断面类型
     */
    @Override
    public List<Map> selectBusWaterAutomonitorevaluateNewHourAndItemdataList(BusWaterAutomonitorevaluateHourdata busWaterAutomonitorevaluateHourdata, String itemType) {

       DecimalFormat df = new DecimalFormat("####.####");
        List<Map> mapList = new ArrayList<>();
        busWaterAutomonitorevaluateHourdata.setIsitontimedata(0);
        busWaterAutomonitorevaluateHourdata.setStartTime(DateUtils.addDay(new Date(), -3));
        busWaterAutomonitorevaluateHourdata.setEndTime(new Date());
        if(!"1".equals(busWaterAutomonitorevaluateHourdata.getIsoverstandard())){
            busWaterAutomonitorevaluateHourdata.setIsoverstandard(null);
        }
        List<BusWaterAutomonitorevaluateHourdata> list = selectBusWaterAutomonitorevaluateNewHourdataList(busWaterAutomonitorevaluateHourdata);
        //查询标准值
        Map<String, Object>standardcategoryMap = new HashMap<>();
        standardcategoryMap.put("waterBody", "1");
        List<Map<String, Object>> wqBasStandardcategorylist = publicToolsMapper.busStandardcategorylist(standardcategoryMap);

        //查询监测因子配置
        if (!CollectionUtils.isEmpty(list)) {
            //获取检测因子配置
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode(itemType);
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            //参与评价的因子
            List<Map<String, Object>> itemEvaluteList = itemList.stream().filter(s->s.get("isEvalute").equals("1")).collect(Collectors.toList());
            List<String> itemCodeList = itemEvaluteList.stream().map(s->StringUtils.getString(s.get("itemCode"))).collect(Collectors.toList());
            //获取监测项目数据
            BusWaterAutomonitorHourdata param = new BusWaterAutomonitorHourdata();
            if (StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getSegmentid()) && busWaterAutomonitorevaluateHourdata.getSegmentid().contains(",")) {
                param.setSegmentidList(Arrays.asList(busWaterAutomonitorevaluateHourdata.getSegmentid().split(",")));
                param.setSegmentid(null);
            }if(StringUtils.isNotEmpty(busWaterAutomonitorevaluateHourdata.getSegmentid()) ){
                param.setSegmentid(busWaterAutomonitorevaluateHourdata.getSegmentid());
            }
            if (!itemList.isEmpty()) {
                List<String> ItemcodeList = new ArrayList<>();
                for (Map<String, Object> stringObjectMap : itemList) {
                    ItemcodeList.add(StringUtils.getString(stringObjectMap.get("itemCode")));
                }
                param.setItemcodeList(ItemcodeList);
                param.setItemcode(null);
            }

            param.setStartTime(DateUtils.addDay(new Date(), -3));
            param.setEndTime(new Date());
            List<BusWaterAutomonitorHourdata> hourdataList = busWaterAutomonitorHourdataService.selectBusWaterAutomonitorHourdataList(param);
//查询的小时评价数据列表，筛选出每个断面最新的一条数据
            // 按断面ID分组，并取每个分组中时间最新的记录
            Map<String, BusWaterAutomonitorevaluateHourdata> latestDataMap = list.stream()
                    .collect(Collectors.toMap(
                            BusWaterAutomonitorevaluateHourdata::getSegmentid, // 按断面ID分组
                            item -> item, // 保存完整对象
                            (existing, replacement) -> { // 合并冲突时保留时间较新的
                                Date existingTime = existing.getSampletime();
                                Date replacementTime = replacement.getSampletime();
                                return existingTime != null && replacementTime != null &&
                                        existingTime.before(replacementTime) ? replacement : existing;
                            }
                    ));

            // 将Map中的值转换为List并按断面ID排序
            list= latestDataMap.values().stream()
                    .sorted(Comparator.comparing(BusWaterAutomonitorevaluateHourdata::getSegmentid))
                    .collect(Collectors.toList());
            for (BusWaterAutomonitorevaluateHourdata waterAutomonitorevaluateHourdata : list) {
                Map map = JSONObject.parseObject(JSONObject.toJSONString(waterAutomonitorevaluateHourdata), Map.class);
                //取出断面、监测时间
                String segmentid = waterAutomonitorevaluateHourdata.getSegmentid();
                Date sampletime = waterAutomonitorevaluateHourdata.getSampletime();//DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", waterAutomonitorevaluateHourdata.getSampletime());
                // 取出断面时间的监测数据，
                List<BusWaterAutomonitorHourdata> segmenthourdata = hourdataList.stream()
                        .filter(item -> item.getSegmentid().equals(segmentid)
                                && item.getSampletime().equals(sampletime)).collect(Collectors.toList());
                //循环监测数据，根据监测项目赋值
                String overMessage = "";
                for (Map<String, Object> stringObjectMap : itemList) {
                    BusWaterAutomonitorHourdata hourdata = segmenthourdata.stream()
                            .filter(item -> item.getItemcode().equals(StringUtils.getString(stringObjectMap.get("itemCode"))))
                            .findFirst().orElse(null);
                    if (hourdata == null) {
                        map.put(StringUtils.getString(stringObjectMap.get("eNName")), "");
                        continue;
                    }
                    String evalue = df.format(hourdata.getEffectivevalue());
                    map.put(StringUtils.getString(stringObjectMap.get("eNName")), evalue);
                    //查看是否超标
                   String itemName=String.valueOf(stringObjectMap.get("itemName"));
                   String isEvalute= StringUtils.getString(stringObjectMap.get("isEvalute"));
                   if("1".equals(isEvalute)){
                       List<Map<String, Object>> sunmapsWaterTypelist =  wqBasStandardcategorylist.stream().filter(s->String.valueOf(s.get("itemCode")).equals(String.valueOf(stringObjectMap.get("itemCode"))) && String.valueOf(s.get("level")).equals(String.valueOf(waterAutomonitorevaluateHourdata.getTargetlevel())) && String.valueOf(s.get("waterType")).equals("1")).collect(Collectors.toList());
                      String isoverstandard= hourdata.getIsoverstandard();
                      BigDecimal effectivevalue= hourdata.getEffectivevalue();
                      String overstandardtimes=hourdata.getOverstandardtimes();
                      if("1".equals(isoverstandard)){
                          overMessage=overMessage+itemName+"(监测值："+df.format(effectivevalue)+stringObjectMap.get("unit");
//                          if(StringUtils.isNotEmpty(overstandardtimes)){
//                              overMessage=overMessage+",倍数："+overstandardtimes;
//                          }
                          if("15DE941F-A221-4D9C-8387-48B0E99F6E25".equals(String.valueOf(stringObjectMap.get("ItemCode")).toUpperCase())){
                              overMessage=overMessage+",标准值：6~9";
                          }else{
                              if(StringUtils.isNotEmpty(sunmapsWaterTypelist) && sunmapsWaterTypelist.size()>0)    {
                                Object  standardValue = sunmapsWaterTypelist.get(0).get("standardValue");
                                  overMessage=overMessage+",标准值:"+standardValue+stringObjectMap.get("unit");
                              }
                          }
                          overMessage=overMessage+")、";
                      }
                   }
                }
                if(StringUtils.isNotEmpty(overMessage)){
                    map.put("overstandarddescribe",overMessage.substring(0,overMessage.length()-1));
                }else{
                    map.put("overstandarddescribe","");
                }

                mapList.add(map);
            }
        }
        return mapList;
    }

}

